//
//  RecentsViewController.m
//  Scanner
//
//  Created by Misaya on 15/6/13.
//  Copyright (c) 2015年 米明. All rights reserved.
//

#import "RecentsViewController.h"
#import "PhotosUploadManager.h"
#import "GoodsPhotosCell.h"
#import "UIImageView+WebCache.h"
#import "DoneGoodsViewController.h"

//自定义
#define CustemColor(r,g,b,a) [UIColor colorWithRed:r/255.f green:g/255.f blue:b/255.f alpha:a]
//积分绿
#define Points_Green CustemColor(106,189,73,1)
//导航栏背景色——水滴蓝
#define Droplet_Blue CustemColor(0,157,232,1)
//粉色
#define Pink_Color CustemColor(246, 139, 136, 1)
//粉红色
#define Pink_Red_Color CustemColor(251, 74, 72, 1)

@interface RecentsViewController ()<UploadTaskDelegate>
{
    NSString * _progress;
}
@property(nonatomic,strong)NSMutableArray * tasks;
@end

@implementation RecentsViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // Do any additional setup after loading the view.
}
-(void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    self.navigationController.navigationBar.barTintColor=[UIColor whiteColor];
}
-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];

    [self initData];
    
    [self creatRightBtnItemWithTitle:@"最近完成"];
    [self creatLeftBtnItemWithTitle:@"重新读取"];
}
-(void)rightBarBtnItem{
    
    DoneGoodsViewController * done = [[DoneGoodsViewController alloc]init];
    
    done.title=[NSString stringWithFormat:@"近期有%d个商品已上传图片",(int)[[[CoreDataManager shareManager]goodsList] count]];
    
    done.hidesBottomBarWhenPushed=YES;
    
    [self.navigationController pushViewController:done animated:YES];
}
-(void)leftBarBtnItem{
    [[PhotosUploadManager manager]clean];
    [self initData];
//    NSString * item = nil;
//    
//    self.navigationItem.leftBarButtonItem=nil;
//    
//    if ([PhotosUploadManager manager].running ==YES) {
//        
//        [[PhotosUploadManager manager] stopRun];
//        
//        item = @"开始";
//        
//        
//    }else{
//        
//        [[PhotosUploadManager manager] startRun];
//        
//        item = @"暂停";
//        
//    }
    //[self creatLeftBtnItemWithTitle:item];
}
-(void)initData{
    
    if ([PhotosUploadManager manager].tasks.allKeys.count<=0) {
        _tasks = nil;
        [self.tableView reloadData];
       // [[PhotosUploadManager manager]setup];
        return;
    }
          _tasks = [[PhotosUploadManager manager] getOrderTasks];
    
         [self.tableView reloadData];

    
//    NSString * item = nil;
//    
//    if ([PhotosUploadManager manager].running ==YES) {
//        item = @"暂停";
//    }else{
//        item = @"开始";
//    }
    
    
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
   
    [self setTitle:[NSString stringWithFormat:@"%d个任务",(int)_tasks.count]];
    if (_tasks.count<=0) {
         self.navigationController.navigationBar.barTintColor=[UIColor whiteColor];
    }
    return _tasks.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString * cellId = @"GoodsPhotosCell";
    
    GoodsPhotosCell * cell = [tableView dequeueReusableCellWithIdentifier:cellId];
    if (!cell) {
        cell = [[[NSBundle mainBundle]loadNibNamed:cellId owner:self options:nil]lastObject];
    }
    UploadTask * task = _tasks[indexPath.row];
    
    task.delegate=self;
    
    dispatch_async(dispatch_get_main_queue(), ^{

        cell.photoImageView.image=[self cutImage:[UIImage imageWithContentsOfFile:task.photoPath] size:CGSizeMake(60, 60)];
        if (task.isUploading) {
            cell.progressLabel.text=_progress;
        }else{
            cell.progressLabel.text=@"";
        }
        
        if (task.isUploading) {
            if (task.succeed) {
                cell.statusLabel.text=@"完成";
                cell.statusLabel.textColor=Droplet_Blue;
            }else{
                cell.statusLabel.text=@"上传中...";
                cell.statusLabel.textColor=Points_Green;
            }
            
        }else{
            cell.statusLabel.text=@"排队中...";
            cell.statusLabel.textColor=[UIColor grayColor];
        }
        
    });
    return cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 70;
}
-(void)uploadTask:(UploadTask *)uploadTask totalBytesWritten:(long long)totalBytesWritten totalBytesExpectedToWrite:(long long)totalBytesExpectedToWrite{
    //NSLog(@"%lld %lld",totalBytesWritten,totalBytesExpectedToWrite);
    if (uploadTask.isUploading) {
        _progress = [NSString stringWithFormat:@"%lld/%lld KB",totalBytesWritten/1024,totalBytesExpectedToWrite/1024];
    }
    
    self.navigationController.navigationBar.barTintColor=Points_Green;
    
    [self.tableView reloadData];
}

-(void)uploadTask:(UploadTask *)uploadTask succeed:(BOOL)succeed{
    [_tasks removeObject:uploadTask];
    [[PhotosUploadManager manager]removeTask:uploadTask];
    self.navigationController.navigationBar.barTintColor=Droplet_Blue;
    [self.tableView reloadData];
}
-(void)uploadTask:(UploadTask *)uploadTask error:(NSError *)error{
    [_tasks removeObject:uploadTask];
    uploadTask.isDid=NO;
    
    self.navigationController.navigationBar.barTintColor=Pink_Red_Color;
    [self.tableView reloadData];
}
//裁剪图片
- (UIImage *)cutImage:(UIImage*)image size:(CGSize)size
{
    //压缩图片
    CGSize newSize;
    
    CGImageRef imageRef = nil;
    
    if ((image.size.width / image.size.height) < (size.width / size.height)) {
        
        newSize.width = image.size.width;
        
        newSize.height = image.size.width * size.height / size.width;
        
        imageRef = CGImageCreateWithImageInRect([image CGImage], CGRectMake(0, fabs(image.size.height - newSize.height) / 2, newSize.width, newSize.height));
        
    } else {
        
        newSize.height = image.size.height;
        
        newSize.width = image.size.height * size.width / size.height;
        
        imageRef = CGImageCreateWithImageInRect([image CGImage], CGRectMake(fabs(image.size.width - newSize.width) / 2, 0, newSize.width, newSize.height));
        
    }
    
    UIImage * img=[UIImage imageWithCGImage:imageRef];
    
    CGImageRelease(imageRef);
    
    return img;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
